const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');
const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const assign = require('lodash/assign');

/*
 request {
 room_id: 1,
 room_name:'红外感应器'，
 vendor：'鸿雁'，
 }
 */
exports.add = async(ctx) => {
  let area = ctx.request.body.area || '';
  let room_name = ctx.request.body.room_name || '';
  let house_type_id = ctx.request.body.house_type_id || 0;
  let create_time = moment().format('YYYY-MM-DD HH:mm:ss');
  let update_time = moment().format('YYYY-MM-DD HH:mm:ss');
  console.log('add_ enter');
  let newroom = {
    area,
    house_type_id,
    room_name,
    update_time,
    create_time,
  };
  try {
    let room = await mysql.query(`INSERT INTO room SET ?`, newroom);
    if (room && room.insertId > 0){
        ctx.body = {
            return: 200,
            room: room.insertId,
            message: "新增room成功"
        };
    } else{
        ctx.body = {
            return: 202,
            room: room.insertId,
            message: "新增room失败"
        };
    }
  }catch (error) {
    let housetypeIds = await mysql.query(`select house_type_id from house_type `);
    if (housetypeIds && housetypeIds.indexOf({house_type_id}) === -1) {
      ctx.body = {
        return: 201,
        message: `housetype 中 不存在 house_type_id = ${house_type_id}的, 或已被删除`,
      };
      return;
    }
    console.log(error);
    ctx.body = {
      return: 205,
      message: '新增时出现错误'+ error.toString(),
    };
  }
}

exports.getList = async(ctx) => {
  let params = ctx.query;
  let counts = params.counts || 10;
  let indexfrom = params.indexfrom || 0;
  let house_type_id =  ctx.params.house_type_id;

  try {
    let results;
    if (house_type_id) {
      results = await mysql.query(`SELECT * FROM room WHERE house_type_id =${house_type_id} ORDER BY room_id LIMIT ${indexfrom}, ${counts} ` );
    } else {
      results = await mysql.query(`SELECT * FROM room ORDER BY room_id LIMIT ${indexfrom}, ${counts} ` );
    }

    ctx.body = {
      result: 200,
      list:results,
      message: "查询成功"
    };
  }catch (e) {
    ctx.body = {
      result: 205,
      message: "数据库错误"
    };
  }
}

exports.update = async(ctx) => {
  let request_body = ctx.request.body;
  let room_id = request_body.room_id || '';
  let room_name = request_body.room_name || '';
  let update_time = moment().format('YYYY-MM-DD HH:mm:ss');
  if (room_id <= 0 || room_name === ''){
      ctx.body = {
          result: 201,
          message: "请检查参数"
      };
      return;
  }
  try {
    let selectRows = await mysql.query(`SELECT * FROM room WHERE room_id = ?`, room_id);
    if (selectRows.length > 0) {
      let update_date = assign({},selectRows[0], ctx.request.body, { update_time });
      console.log(selectRows[0]);
      let ret = await mysql.query(`UPDATE room SET ? WHERE room_id = ${room_id}`, update_date);
      console.log(ret);
      if (!ret || ret.insertId === -1) {
        ctx.body = {
          result: 202,
          message: "更新失败"
        };
      } else {
        ctx.body = {
          result: 200,
          message: "更新成功"
        };
      }
    } else {
      ctx.body = {
        result: 203,
        message: "对象不存在或者已删除"
      };
    }
  }catch (e) {
    ctx.body = {
      result: 204,
      message: "更新失败"+e.toString()
    };
  }

}

exports.delete = async(ctx) => {
  let room_id = ctx.params.room_id;

  try {
      let ret = await mysql.query(`delete  from room  WHERE room_id = ${room_id}`);
      if (!ret || ret.affectedRows === 0){
          ctx.body = {
              result: 202,
              message: "对象不存在或已删除"
          };
      } else {
          ctx.body = {
              result: 200,
              message: "删除成功"
          };
      }
  }catch (e) {
      ctx.body = {
          result: 205,
          message: "错误"+e.toString()
      };
  }
}

exports.getDetail = async(ctx) => {
  let room_id = ctx.params.room_id;

  if (room_id <= 0){
    ctx.body = {
        result: 201,
        message: "无效的room_id"
    };
    return;
  }
    try {
        let selectRooms = await mysql.query(`SELECT * FROM room where room_id = ${room_id}`);
        if (selectRooms.length > 0){
            roomResult = selectRooms[0];
            selectScenarios = await mysql.query(`SELECT scenario_id,scenario_type,scenario_name,pic_url AS scenario_icon,house_type_id,triggering_condition,matching_condition,action FROM v_room_scenario where room_id = ${room_id}`);
            selectProducts = await mysql.query(`SELECT product_id,name AS product_name,vendor_name,model_type_name,pic_url AS product_icon,model_name,tag AS link FROM v_temp_device_detail where room_id = ${room_id}`);

            roomResult.room_count = selectProducts.length;
            roomResult.scenario_list = selectScenarios;
            roomResult.room_list = selectProducts;
            ctx.body = {
                result: 200,
                resultInfo:roomResult,
                message: "查询成功"
            };
        }else{
            ctx.body = {
                result: 202,
                message: "查询失败"
            };
        }

    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

